package com.tpay.server;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.Transactional;

public class GeneralDaoImpl implements GeneralDao {
	private static Logger logger = LoggerFactory.getLogger(GeneralDaoImpl.class);
	
	@Inject
	private Provider<EntityManager> provider;
	private EntityManager em;
	
	public GeneralDaoImpl() {
		logger.debug("GeneralDaoImpl 생성");
	}
	
	@Override
	public EntityManager getEm() {
		if(provider != null) {
			EntityManager temp = provider.get();
			
			if(em == null || em != temp) {
				logger.debug("em 생성");
				em = temp;
			}
		}
		
		return em;
	}

	@Override
	@Transactional
	public void insert(Object entity) {
		getEm().persist(entity);
	}
	
	@Override
	@Transactional
	public <T> T update(T entity) {
		return getEm().merge(entity);
	}

	@Override
	@Transactional
	public <T> void deleteById(Class<T> type, Serializable id) {
		Query query = getEm().createQuery("delete from " + type.getSimpleName() + " e where e.id=?").setParameter(1, id);
		query.executeUpdate();
	}

	@Override
	@Transactional
	public <T> void deleteAll(Class<T> type) {
		Query query = getEm().createQuery("delete from " + type.getSimpleName());
		query.executeUpdate();
	}

	@Override
	public long countAll(Class<?> type) {
		return (Long)getEm().createQuery("select count(t) from " + type.getSimpleName() + " t").getSingleResult();
	}
	
	@Override
	public <T> T find(Class<T> type, Serializable primaryKey) {
		return getEm().find(type, primaryKey);
	}
	
	@Override
	public <T> List<T> findAll(Class<T> type) {
		return getEm().createQuery("from " + type.getSimpleName(), type).getResultList();
	}

	@Override
	public <T> T getReference(Class<T> type, Serializable id) {
		return getEm().getReference(type, id);
	}
}
